﻿using B.S.BasicData.API.Read.Application.Command.Menu;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace B.S.BasicData.API.Read.Application.Handler.Menu
{
    /// <summary>
    /// 根据角色Id获取菜单请求命令处理类
    /// </summary>
    public class GetMenuByRoleIdHandler:IRequestHandler<GetMenuByRoleIdCommand,ApiResult<List<RoleMenuDTO>>>
    {
        IBaseRepository<RoleMenuModel> roleMenuRep;
        IBaseRepository<MenuModel> menuRep;

        public GetMenuByRoleIdHandler(IBaseRepository<RoleMenuModel> roleMenuRep, IBaseRepository<MenuModel> menuRep)
        {
            this.roleMenuRep = roleMenuRep;
            this.menuRep = menuRep;
        }

        public Task<ApiResult<List<RoleMenuDTO>>> Handle(GetMenuByRoleIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<RoleMenuDTO>> res = new ApiResult<List<RoleMenuDTO>>();

                var list=request.roleId.Split(',').ToList();
                var rolemenus = roleMenuRep.GetAll().Where(x => !x.IsDeleted);

                List<int> model=new List<int>();

                foreach (var item in list)
                {
                    var menuids = roleMenuRep.GetAll().Where(x => x.RoleId == Convert.ToInt32(item)).Select(x => x.MenuId).ToList();
                    model.AddRange(menuids);
                }

                var menu = menuRep.GetAll().Where(x => !x.IsDeleted);
                var data = Find(0, menu.ToList(), model);
                res.Msg = "获取菜单权限成功";
                res.Data = data;
                res.Code = ApiEnum.Success;
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }

        private List<RoleMenuDTO> Find(int pid, List<MenuModel> ids, List<int> mid)
        {
            var res=ids.Where(x=>x.P_ID==pid&&mid.Contains(x.Id)).ToList();
            List<RoleMenuDTO> roleMenus = new List<RoleMenuDTO>();
            foreach (var item in res)
            {
                roleMenus.Add(new RoleMenuDTO
                {
                    MenuName = item.MenuName,
                    Url = item.Url,
                    Children = Find(item.Id, ids, mid)
                });
            }
            return roleMenus;
        }
    }
}
